package cn.time1024.time_app

import android.os.Bundle
import com.google.android.material.bottomnavigation.BottomNavigationView
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.setupActionBarWithNavController
import androidx.navigation.ui.setupWithNavController
import cn.time1024.time_app.databinding.ActivityMainBinding
import com.example.timeassistant.network.TokenManager
import android.Manifest
import android.os.Build
import android.content.pm.PackageManager
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import android.util.Log

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // 将 Toolbar 作为 ActionBar，避免 NoActionBar 主题导致的崩溃
        setSupportActionBar(binding.toolbar)

        val navView: BottomNavigationView = binding.navView

        val navHostFragment = supportFragmentManager
            .findFragmentById(R.id.nav_host_fragment_activity_main) as NavHostFragment
        val navController = navHostFragment.navController
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        val appBarConfiguration = AppBarConfiguration(
            setOf(
                R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications
            )
        )
        setupActionBarWithNavController(navController, appBarConfiguration)
        navView.setupWithNavController(navController)

        // 应用启动后尝试恢复已保存的 Token
        val prefs = getSharedPreferences("auth_prefs", MODE_PRIVATE)
        val savedToken = prefs.getString("auth_token", null)
        if (!savedToken.isNullOrBlank()) {
            TokenManager.token = savedToken
        }

        // ====== Android 13+ 通知运行时权限申请 ======
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            val granted = ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED
            if (!granted) {
                ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.POST_NOTIFICATIONS), 1000)
            }
        }
        // 处理来自 JPush 的深链导航
        handleJPushIntent(intent, navController)
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 1000) {
            val ok = grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED
            Log.d("JPush", "POST_NOTIFICATIONS permission granted=${ok}")
        }
    }
    override fun onNewIntent(intent: android.content.Intent?) {
        super.onNewIntent(intent)
        if (intent == null) return
        val navHostFragment = supportFragmentManager
            .findFragmentById(R.id.nav_host_fragment_activity_main) as NavHostFragment
        val navController = navHostFragment.navController
        handleJPushIntent(intent, navController)
    }

    /**
     * 处理来自 JPush 的深链导航：跳转通知中心或通知详情
     */
    private fun handleJPushIntent(intent: android.content.Intent, navController: androidx.navigation.NavController) {
        val fromJPush = intent.getBooleanExtra("from_jpush", false)
        if (!fromJPush) return
        val id = intent.getLongExtra("notificationId", 0L)
        binding.navView.selectedItemId = R.id.navigation_notifications
        if (id > 0) {
            val args = android.os.Bundle().apply { putLong("notificationId", id) }
            navController.navigate(R.id.navigation_notification_detail, args)
        } else {
            navController.navigate(R.id.navigation_notification_center)
        }
    }
}